import { login } from '@/api/user'
import {
  getToken, setToken,
  getUserInfo, setUserInfo,
  getUserMenus, setUserMenus,
  getAllowedPaths, setAllowedPaths,
  getRoutesAdded, setRoutesAdded,
  clearAllUserData
} from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  // 从localStorage恢复数据
  const userInfo = getUserInfo()
  return {
    token: getToken(),
    name: userInfo?.name || '',
    avatar: userInfo?.avatar || '',
    menus: getUserMenus(), // 后端返回的可访问菜单
    routesAdded: getRoutesAdded(), // 是否已根据菜单动态注入路由
    allowedPaths: getAllowedPaths() // 根据菜单推导出的可访问路由完整路径集合
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.name = name
    // 更新用户信息到localStorage
    const userInfo = getUserInfo() || {}
    userInfo.name = name
    setUserInfo(userInfo)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
    // 更新用户信息到localStorage
    const userInfo = getUserInfo() || {}
    userInfo.avatar = avatar
    setUserInfo(userInfo)
  },
  SET_MENUS: (state, menus) => {
    state.menus = Array.isArray(menus) ? menus : []
    setUserMenus(state.menus)
  },
  SET_ROUTES_ADDED: (state, added) => {
    state.routesAdded = !!added
    setRoutesAdded(state.routesAdded)
  },
  SET_ALLOWED_PATHS: (state, paths) => {
    state.allowedPaths = Array.isArray(paths) ? paths : []
    setAllowedPaths(state.allowedPaths)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        // 保存后端返回的菜单权限
        commit('SET_MENUS', data.pathPermsList)
        commit('SET_ROUTES_ADDED', false)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info（本地回退版）：不依赖后端接口，避免刷新时 404
  getInfo({ commit }) {
    return new Promise((resolve) => {
      const fallback = {
        name: 'Admin',
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
      }
      commit('SET_NAME', fallback.name)
      commit('SET_AVATAR', fallback.avatar)
      resolve(fallback)
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve) => {
      // 直接清除本地token和状态，不调用后端logout
      // 因为后端可能没有logout接口
      clearAllUserData() // 清除所有用户相关数据
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      clearAllUserData() // 清除所有用户相关数据
      commit('RESET_STATE')
      resolve()
    })
  },

  setRoutesAdded({ commit }, added) {
    commit('SET_ROUTES_ADDED', added)
  },

  setAllowedPaths({ commit }, paths) {
    commit('SET_ALLOWED_PATHS', paths)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

